package com.jeomo.mem.starter.service.impl;

import com.jeomo.base.starter.service.impl.BaseServiceImpl;
import com.jeomo.common.core.exception.BusinessException;
import com.jeomo.common.core.util.BeanCopyUtil;
import com.jeomo.common.core.util.StringUtils;
import com.jeomo.masterdata.starter.entity.Goods;
import com.jeomo.masterdata.starter.enums.UseScopeEnum;
import com.jeomo.masterdata.starter.service.IGoodsService;
import com.jeomo.mem.starter.entity.*;
import com.jeomo.mem.starter.enums.MemberPointsSrcEnum;
import com.jeomo.mem.starter.exception.MemberCardException;
import com.jeomo.mem.starter.mapper.MemberPointsSuppleDetailMapper;
import com.jeomo.mem.starter.mapper.MemberPointsSuppleMapper;
import com.jeomo.mem.starter.service.IMemPointsSuppleService;
import com.jeomo.mem.starter.service.IMemberCardService;
import com.jeomo.mem.starter.service.IMemberPointsService;
import com.jeomo.mem.starter.sysoption.PointsValiditySysOption;
import com.jeomo.shiro.util.LoginSessionUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * 会员积分补录
 *
 * @author:Jackpot
 * @create 2020-10-14 11:49
 * @description:
 */
@Service
@Transactional
public class MemPointsSuppleServiceImpl extends BaseServiceImpl<MemberPointsSuppleDetailMapper, MemberPointsSuppleDetail>
        implements IMemPointsSuppleService {

    @Resource
    private IMemberPointsService memberPointsService;
    @Resource
    private MemberPointsSuppleMapper memberPointsSuppleMapper;
    @Resource
    private MemberPointsSuppleDetailMapper memberPointsSuppleDetailMapper;
    @Resource
    private IMemberCardService memberCardService;
    @Resource
    private IGoodsService goodsService;
    @Resource
    private PointsValiditySysOption pointsValiditySysOption;
    @Resource
    private MemberLevelExeService memberLevelExeService;

    @Override
    public int insertPointSupple(MemberPointsSupplement memPointsSupplement) {

        //校验兑换时间是否过期
        LocalDate today = LocalDate.now();
        pointsValiditySysOption.load();
        Integer convertDeadline = pointsValiditySysOption.getConvertDeadline();
        LocalDateTime payTime = memPointsSupplement.getPayTime();
        if (payTime.plusDays(convertDeadline).toLocalDate().compareTo(today)<0){
            throw new BusinessException("兑换时间已过期, "+convertDeadline+" 天前的消费积分不可以再次兑换!");
        }
        //校验补录信息是否重复
        String orderNo = memPointsSupplement.getOrderNo();
        String merchant = memPointsSupplement.getMerchant();
        Double payAmount = memPointsSupplement.getPayAmount();
        int i = memberPointsSuppleMapper.queryRepeat(orderNo, merchant, payAmount);
        if (i>0){
            throw new BusinessException("订单号为 "+orderNo+" 的消费信息已补录, 不可以重复补录!");
        }
        //新增补录
        addSupple(memPointsSupplement);
        String code = memPointsSupplement.getCode();
        //积分变动
        MemberPointsUpdate memberPointsUpdate = BeanCopyUtil.copyProperties(memPointsSupplement,MemberPointsUpdate.class);
        memberPointsUpdate.setLevelCode(memPointsSupplement.getMemberLevel());
        Integer acquirePoints = memPointsSupplement.getAcquirePoints();
        memberPointsUpdate.setPointsChange(acquirePoints!=null?acquirePoints:0);
        memberPointsUpdate.setPointsOld(memPointsSupplement.getCurrPoints().intValue());
        memberPointsUpdate.setSrcCode(code);
        memberPointsUpdate.setSrcTypeCode(MemberPointsSrcEnum.SUPPLEMENT.getCode());
        memberCardService.updateMemberPoints(memberPointsUpdate);
        //记录消费明细
        MemberConsumeDetail memberConsumeDetail = BeanCopyUtil.copyProperties(memPointsSupplement,MemberConsumeDetail.class);
        memberConsumeDetail.setPayAmount(payAmount);
        memberConsumeDetail.setPayTime(payTime);
        memberConsumeDetail.setSrcId(code);
        memberConsumeDetail.setSrcType(MemberPointsSrcEnum.SUPPLEMENT.getCode());
        memberConsumeDetail.setCode(null);
        memberConsumeDetail.setId(null);
        memberCardService.recordConsumeDetail(memberConsumeDetail);

        MemberLevelExeUpdate memberLevelExeUpdate = BeanCopyUtil.copyProperties(memberPointsUpdate, MemberLevelExeUpdate.class);
        memberLevelExeUpdate.setAcquirePoints(memberPointsUpdate.getPointsChange());
        memberLevelExeUpdate.setAcquireAmount(payAmount);
        memberLevelExeService.updateLevelExe(memberLevelExeUpdate);

        return 1;
    }

    public void addSupple(MemberPointsSupplement memPointsSupplement){
        memPointsSupplement.setOrg(LoginSessionUtil.getCurrentLoginInfo().getOrgCode());
        memPointsSupplement.setHandleTime(LocalDateTime.now());

        String merchant = memPointsSupplement.getMerchant();
        Double payAmount = memPointsSupplement.getPayAmount();
        String memberLevel = memPointsSupplement.getMemberLevel();
        //计算获取积分
        MemberPointsRuleExe pointsRule = null;
        List<Goods> goods = goodsService.selectGoodsByMerchantCodes(merchant);
        String goodsCode = null;
        if (goods!=null && !goods.isEmpty()) {
            goodsCode = goods.get(0).getCode();
            pointsRule = memberPointsService.getPointsRuleByGoods(memberLevel, goodsCode);
        }else{
            pointsRule = memberPointsService.getPointsRuleByGoods(memberLevel, merchant);
        }
        int acquirePoints = memberPointsService.getPoints(pointsRule, payAmount);
        memPointsSupplement.setAcquirePoints(acquirePoints);
        if (acquirePoints>0){//计算积分过期时间
            LocalDate validityDate = pointsValiditySysOption.getValidityDate(memPointsSupplement.getPayTime().toLocalDate());
            memPointsSupplement.setExpiredTime(validityDate);
        }

        int masterResult = memberPointsSuppleMapper.insert(memPointsSupplement);
        if(masterResult != 1){
            throw new MemberCardException("会员积分补录信息新增失败!");
        }
        //如果命中积分规则,则增加补录明细
        if (pointsRule!=null){
            String code = memPointsSupplement.getCode();
            List<MemberPointsSuppleDetail> memPointsSuppleDetail = new ArrayList<>();
            MemberPointsSuppleDetail suppleDetail = new MemberPointsSuppleDetail();
            suppleDetail.setGoodsCode(goodsCode);
            suppleDetail.setAmount(payAmount);
            suppleDetail.setRule(pointsRule.getRuleCode());
            suppleDetail.setPointsBasic(acquirePoints);
            suppleDetail.setPointsTotal(acquirePoints);
            memPointsSuppleDetail.add(suppleDetail);
            insertPointSuppleDetail(memPointsSuppleDetail, code);
        }
    }



    @Override
    public void insertPointSuppleDetail(List<MemberPointsSuppleDetail> memberPointsSuppleDetails, String code) {
        if (memberPointsSuppleDetails.isEmpty()) return;
        Iterator<MemberPointsSuppleDetail> iterator = memberPointsSuppleDetails.iterator();
        while (iterator.hasNext()){
            MemberPointsSuppleDetail suppleDetail = iterator.next();
            suppleDetail.setpCode(code);
        }
        saveBatch(memberPointsSuppleDetails);
    }
}
